<template>
  <view
    class="wrapper"
    :style="specialStyle"
    @touchstart="$emit('closeBubble')"
  >
    <view class="majorFilterContainer">
      <!-- <scroll-view :scroll-x="true" class="firstListContainer" scroll-with-animation
        :scroll-into-view='scollFirstToView'>
        <view v-for="item,index in majorFirstList" :key="index"
          :class="{'firstListItem':true, 'selectedFirst':item.navId==selectedFirstId}" :id="`first-${index}`"
          @click="handleFirstItemClick(item,index)">
          {{item.navName}}
        </view>
      </scroll-view> -->
      <view class="firstListContainer">
        <u-tabs
          :list="majorFirstList"
          bg-color="transparent"
          :height="100"
          inactive-color="#222"
          active-color="#222"
          :bar-style="{ display: 'none' }"
          name="navName"
          is-scroll="true"
          :current="selectedFirstIndex"
          @change="handleFirstItemClick"
          :gutter="28"
          :active-item-style="tabActiveStyle"
        >
        </u-tabs>
      </view>

      <scroll-view
        :scroll-y="scrollEabled"
        scroll-with-animation
        class="recommendArea"
        :style="{
          paddingBottom: sign == 'ZHITU_TOC_SERVICE' ? '300rpx' : '56rpx'
        }"
        v-if="selectedFirstIndex == 0"
      >
        <view class="recommendAreaContent" v-if="recommendList.length">
          <view
            class="recommendItem"
            v-for="(item, index) in recommendList"
            :key="index"
            @click="handleThirdItemClick(item)"
          >
            <image class="img" :src="item.coverImg" mode="aspectFill" />
            <view class="text-box">
              <view class="title">{{ item.positionName }}</view>
              <view class="desc">{{ item.positionDesc }}</view>
              <view class="num">{{ item.readNum }}</view>
            </view>
          </view>
        </view>
        <view class="tips" v-if="recommendList.length">没有更多啦</view>
        <view class="empty" v-else>
          <Empty
            :baseImg="emptyImg"
            text="暂无推荐职业"
            textColor="#888"
            :fontWeight="400"
          />
        </view>
      </scroll-view>
      <view v-else class="mainListContainer">
        <scroll-view
          :scroll-y="scrollEabled"
          :scroll-top="scrollSecondTop"
          scroll-with-animation
          class="secondPositionList"
        >
          <view
            :class="{
              SecondPositionItem: true,
              'u-line-2': true,
              selectedSecond: item.navId == selectedSecondId
            }"
            v-for="(item, index) in secondPositionList"
            :key="index"
            @click="handleSecondItemClick(item, index)"
          >
            <span v-if="item.navName == '热门'" class="hotSecondPosition">
              <img
                src="https://img3.job1001.com/ypMp/elan/images/career/hotSecondPosition.png"
              />
              {{ item.navName }}</span
            >
            <span v-else>{{ item.navName }}</span>
          </view>
        </scroll-view>
        <scroll-view
          :scroll-y="scrollEabled"
          scroll-with-animation
          class="thirdPositionList"
          :scroll-into-view="scollThirdToView"
          @scroll.native="handleScroll"
          ref="scollView"
        >
          <view
            class="ThirdPositionItem"
            v-for="(item, index) in secondPositionList"
            :key="index"
            :id="`third-${index}`"
          >
            <view :class="{ thirdTitle: true, fixedTitle: item.isFixTitle }">
              <template v-if="item.navName == '热门'">
                {{ item.navName }}
                <text class="titleTip"
                  >大家都在搜的{{ selectedFirstName }}专业</text
                ></template
              >
              <template v-else>
                {{ item.navName }}
                <text class="titleTip"
                  >({{ item.children.length || '0' }}个)</text
                ></template
              >
            </view>
            <view class="thirdChildrenList">
              <view
                class="thirdChildrenItem"
                v-for="(_item, _index) in item.children"
                :key="_index"
                @click="handleThirdItemClick(_item)"
              >
                <view class="thirdChildrenItemTitle"> {{ _item.navName }}</view>
                <view class="thirdChildrenItemTags">
                  <view class="tagItem" v-if="_item.tagTimeDesc">{{
                    _item.tagTimeDesc
                  }}</view>
                  <view class="tagItem" v-if="_item.tagDesc">{{
                    _item.tagDesc
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getNavigationTree,
  getSonNavigationTree,
  getRecommendReport
} from '@/api/modules/career';
import { reqZhituGetCareer } from '@/api/modules/company.js';
import Empty from '@/components/Empty';
export default {
  name: 'mainFilter',
  components: {
    Empty
  },
  props: {
    cateType: {
      type: String,
      default: '30'
    },
    scrollEabled: {
      type: Boolean,
      default: false
    },
    specialStyle: {
      type: Object,
      default: () => {}
    },
    relevanceCareerId: {
      type: String,
      default: '1'
    },
    sign: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      emptyImg: this.$imgBaseSelf + 'common/empty.png',
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      positionTree: [], // 职业树
      recommendList: [], // 推荐职业
      showRecommend: false,

      majorFirstList: [],
      secondPositionList: [],
      ThirdPositionList: [],
      selectedFirstId: '', //第一层选中的id
      selectedFirstName: '', //第一层选中的名字
      selectedFirstIndex: '', //第一层选中的下标
      scollFirstToView: '', //控制第一层筛选容器滚动的变量
      selectedSecondId: '', //第二层选中的id
      selectedSecondIndex: 0, //第二层选中的下标
      scrollSecondTop: 0, //第二层的滚动高度
      scollThirdToView: '', //控制第三层筛选容器滚动的变量
      distance: 0,
      isClickTab: false, //是否是点击滚动
      secondHeightArr: [], //第二层每一个专业的高度
      heightArr: [], //第三层每一个二级专业的高度
      tabActiveStyle: {
        'justify-content': 'center',
        'align-items': 'center',
        border: '4rpx solid #f75a3e',
        background: 'linear-gradient(180deg, #ffece9 0%, #ffffff 100%)',
        'border-radius': '12rpx',
        'line-height': '98rpx'
      },
      recommendHeight: 0
    };
  },
  methods: {
    //专科本科改变将index设为0
    currentIndexZero() {
      this.selectedFirstIndex = 0;
    },

    // //获取第一层
    reqgetNavigationTree() {
      getNavigationTree({})
        .then((res) => {
          if (res.code == 200) {
            this.majorFirstList = res.data || [];

            this.majorFirstList.unshift({
              navId: '-1',
              navName: '推荐'
            });
            if (res.data.length) {
              this.selectedFirstId = res.data[0].navId;
              this.selectedFirstName = res.data[0].navName;
              this.reqgetSonNavigationTree(res.data[0].navId);
              this.scollFirstToView = ''; //需要先重置一下
              setTimeout(() => {
                this.scollFirstToView = 'first-0'; //重置一下第三层滚动
              });
            }
          }
        })
        .catch((err) => {});
    },
    // 获取第二层
    reqgetSonNavigationTree(navId) {
      //如果是推荐就不请求
      if (navId == -1) return;
      //根据一级专业Id获取二级和三级列表，每次tab点击都会调用
      getSonNavigationTree({
        navId: navId,
        levelNum: 1
      })
        .then((res) => {
          if (res.code == 200) {
            this.secondPositionList = res.data[0].children || [];
            this.selectedSecondId = res.data[0].children[0].navId;
            this.cacSecondHeight();
            this.cacHeight();
            this.selectedSecondIndex = 0;
            this.isClickTab = true;
            setTimeout(() => {
              this.isClickTab = false;
            }, 300);
            this.scollThirdToView = ''; //需要先重置一下
            setTimeout(() => {
              this.scollThirdToView = 'third-0'; //重置一下第三层滚动
              this.$set(
                this.secondPositionList[this.selectedSecondIndex],
                'isFixTitle',
                true
              );
            });
          }
        })
        .catch((err) => {});
    },
    handleFirstItemClick(index) {
      this.selectedFirstIndex = index;
      if (index == 0) {
        this.showRecommend = true;
        return;
      }
      this.selectedFirstId = '';
      const item = this.majorFirstList[index];
      this.selectedFirstId = item.navId;
      this.selectedFirstName = item.navName;
      this.scollFirstToView = 'first-' + index;
      this.reqgetSonNavigationTree(item.navId);
    },
    handleSecondItemClick(item, index) {
      //如果你在好奇为什么初始情况下点击二级没有定位三级，那是因为这时候scrollEabled是false，所以不会滚动
      // 所以这里直接短暂的把scrollEabled设置为true，然后再设置为false，这样就会触发滚动了
      if (this.scrollEabled == false) {
        this.$emit('update:scrollEabled', true);
        setTimeout(() => {
          this.$emit('update:scrollEabled', false);
        }, 1000);
      }
      if (this.isClickTab) return;
      this.isClickTab = true;
      setTimeout(() => {
        this.isClickTab = false;
      }, 500);
      this.selectedSecondId = item.navId;
      this.selectedSecondIndex = index;
      this.scollThirdToView = null;

      this.$nextTick(() => {
        this.scollThirdToView = 'third-' + index;
      });
    },
    handleThirdItemClick(_item) {
      this.$emit(
        'handlePositionSelect',
        _item.ylPositionId || _item.valueId || _item.positionId
      );
    },

    handleScroll(e) {
      if (this.isClickTab) return;
      let scrollTop = e.detail.scrollTop; //获取距离顶部的距离;
      //现在的item的高度
      const nowHeight = this.heightArr[this.selectedSecondIndex];
      //上一个的高度
      const preHiehgt = this.heightArr[this.selectedSecondIndex - 1];
      //处理第三层的滚动
      if (scrollTop > nowHeight) {
        if (this.secondPositionList.length > this.selectedSecondIndex + 1) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex + 1].navId;
          this.selectedSecondIndex += 1;
          //如果滚动到顶部以后了，那就得固定一下title
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            'isFixTitle',
            true
          );
        } else {
          console.log(
            '🚀 ~ file: majorFilterListAI.vue:217 ~ secondPositionList.length:',
            this.secondPositionList.length
          );
        }
      } else if (scrollTop < preHiehgt) {
        if (this.secondPositionList[this.selectedSecondIndex - 1]) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex - 1].navId;
          this.selectedSecondIndex -= 1;
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            'isFixTitle',
            true
          );
        }
      }
      //处理二级跟随滚动
      this.scrollSecondTop =
        this.secondHeightArr[this.selectedSecondIndex] -
        parseInt(this.specialStyle.height.slice(0, -2) / 2);
    },
    cacHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll('.ThirdPositionItem').boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.heightArr = list;
        });
      });
    },
    //计算二级的每个高度
    cacSecondHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll('.SecondPositionItem').boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.secondHeightArr = list;
        });
      });
    },

    // 获取职业列表(数据写死固定的)
    getRecommendReportFn() {
      let params = {
        dataId: this.personId,
        templateCode: 'career_report'
      };
      getRecommendReport(params)
        .then((res) => {
          if (res.code == 200) {
            this.recommendList = res.data;
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: 'error'
            });
          }
        })
        .catch((err) => {});
    }
  },

  created() {
    this.reqgetNavigationTree();
    this.getRecommendReportFn();

    let height = 0;
    uni.getSystemInfo({
      success: function (res) {
        console.log('🚀 ~ created ~ res:', res);
        if (res.statusBarHeight == 20) {
          height = res.screenHeight - 246;
        } else {
          height = res.screenHeight - 328;
        }
      }
    });
    this.recommendHeight = height;
    console.log('🚀 ~ created ~ recommendHeight:', height);
  },
  watch: {
    cateType(newValue, oldValue) {
      if (newValue) {
        this.reqgetNavigationTree();
        this.getRecommendReportFn();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  margin-top: 26rpx;
  width: 100vw;
  min-height: 400rpx;
  .majorFilterContainer {
    .firstListContainer {
      height: 100rpx;
      width: 100vw;
      margin-bottom: 54rpx;
      background-color: transparent;
      .firstListItem {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        scroll-snap-align: center; /* 设置吸附位置 */
        height: 100rpx;
        padding: 0 28rpx;
        margin-right: 16rpx;
        border-radius: 12rpx;
        border: 2rpx solid #e4e5f5;
        background: linear-gradient(180deg, #ebf5fe 0%, #ffffff 100%);
        &.selectedFirst {
          border: 4rpx solid #f75a3e;
          background: linear-gradient(180deg, #ffece9 0%, #ffffff 100%);
        }
        &:last-of-type {
          margin-right: 0rpx;
        }
      }
    }
  }

  .recommendArea {
    height: calc(100vh - 450rpx);
    background: #fff;
    padding: 0rpx 32rpx 0 32rpx;
    box-sizing: border-box;
    .recommendAreaContent {
      .recommendItem {
        display: flex;
        align-items: center;
        height: 202rpx;
        margin-bottom: 38rpx;
        .img {
          width: 144rpx;
          height: 202rpx;
          border-radius: 8rpx;
        }
        .text-box {
          margin-left: 24rpx;
          width: calc(100% - 168rpx);
          display: flex;
          flex-direction: column;
          height: 100%;
          .title {
            width: 100%;
            font-weight: 600;
            font-size: 32rpx;
            line-height: 56rpx;
            color: #333333;
            margin-bottom: 12rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .desc {
            width: 100%;
            font-size: 26rpx;
            color: #aaaaaa;
            line-height: 36rpx;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          .num {
            font-size: 24rpx;
            color: #bfbfbf;
            line-height: 36rpx;
            margin-top: auto;
          }
        }
      }
    }
    .tips {
      font-size: 28rpx;
      color: #999999;
      text-align: center;
      margin: 24rpx 0;
    }
  }
  .mainListContainer {
    display: flex;
    // justify-content: start;
    padding-bottom: 70rpx;
    .secondPositionList {
      height: calc(100vh - 570rpx);
      background-color: #f4f6f8;
      max-width: 214rpx;
      .SecondPositionItem {
        display: flex;
        // justify-content: center;
        align-items: center;
        // width: 212rpx;
        padding-left: 32rpx;
        height: 100rpx;
        background: #f4f6f8;
        color: #666666;
        overflow: unset !important;
        span {
          // display: inline-flex;
          // justify-content: center;
          // align-items: center;
          text-align: left;
          max-width: 160rpx;
          font-size: 28rpx;
          // overflow: hidden;
          // white-space: nowrap;
          // text-overflow: ellipsis;
        }
        .hotSecondPosition {
          display: inline-flex;
          justify-content: flex-start;
          align-items: center;
          img {
            width: 28rpx;
            height: 36rpx;
            margin-right: 14rpx;
          }
        }
      }
      .selectedSecond {
        position: relative;
        background: #ffffff;
        font-weight: bold;
        color: #222222;
        &::after {
          content: '';
          position: absolute;
          bottom: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + 'career/positionDictionary/radiuBorder.png');
          background-repeat: no-repeat;
          background-size: 100% 100%;
          z-index: 9999;
        }
        &::before {
          content: '';
          position: absolute;
          top: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + 'career/positionDictionary/topRadiuBorder.png');
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }
    .thirdPositionList {
      position: relative;
      height: calc(100vh - 570rpx);
      background-color: white;
      margin-left: -2rpx;
      .ThirdPositionItem {
        display: flex;
        flex-direction: column;
        border-bottom: 10rpx solid #f4f6f7;
        &:last-of-type {
          overflow: hidden;
          border-bottom: none;
          padding-bottom: 100rpx;
        }
        .thirdTitle {
          display: flex;
          align-items: center;
          width: 538rpx;
          height: 100rpx;
          padding: 0rpx 32rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          .titleTip {
            font-size: 26rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
            line-height: 30rpx;
            padding-left: 16rpx;
          }
        }
        .fixedTitle {
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: white;
        }
        .thirdChildrenList {
          display: flex;
          flex-direction: column;
          .thirdChildrenItem {
            display: flex;
            flex-direction: column;
            // width: 538rpx;
            // min-height: 124rpx;

            padding: 30rpx 0;
            margin: 0 32rpx;
            border-bottom: 1.2rpx solid #f5f5f5;
            .thirdChildrenItemTitle {
              font-size: 28rpx;
              font-family: PingFangSC;
              font-weight: bold;
              color: #222222;
              line-height: 30rpx;
              // margin-bottom: 16rpx;
            }
            .thirdChildrenItemTags {
              display: flex;
              .tagItem {
                display: flex;
                align-items: center;
                height: 30rpx;
                // line-height: 28rpx;
                font-size: 20rpx;
                padding: 0 6rpx;
                background: rgba(255, 119, 49, 0.05);
                border-radius: 6rpx;
                border: 1rpx solid #ff836c;
                color: #fa7259;
                margin-right: 16rpx;
              }
            }
          }
        }
      }
    }
  }
}
.u-tab-item {
  border: none;
  background: #f5f5f5;
}
</style>
